﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Runtime.CompilerServices;

namespace Hu.Core.Domains.Basic.Base
{
    public class HuBaseDbContext : DbContext
    {
        /// <summary>
        /// 数据库名称
        /// </summary>
        private readonly IConfiguration _configuration;
        private readonly string _connectionStringName;

        public HuBaseDbContext(IConfiguration configuration, string connectionStringName = "DefaultConnection")
        {
            _configuration = configuration;
            _connectionStringName = connectionStringName;
        }
#if false
        //protected override async void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    optionsBuilder.ConfigureWarnings(x => x.Ignore(RelationalEventId.PendingModelChangesWarning));
        //    var connectionString = _configuration.GetConnectionString(this._dataBaseName);
        //    optionsBuilder.UseSqlServer(connectionString, x => x.MigrationsHistoryTable("__HuMigrationsHistory"));

        //    //自动迁移
        //    IRelationalDatabaseCreator databaseCreator = this.Database.GetService<IRelationalDatabaseCreator>();
        //    databaseCreator.CreateTables();
        //    await this.Database.MigrateAsync();

        //    base.OnConfiguring(optionsBuilder);
        //}  
#endif

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //modelBuilder.Entity<HuBaseEntity>().HasQueryFilter(x => !x.TagDeleted);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connectionString = _configuration.GetConnectionString(this._connectionStringName);
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException($"未找到数据库 '{_connectionStringName}'的连接配置");
            }
            // 动态选择数据库提供程序（通过配置决定）
            var databaseProvider = _configuration["DatabaseProvider"] ?? "SqlServer";
            switch (databaseProvider.ToLower())
            {
                case "sqlserver":
                    optionsBuilder.UseSqlServer(connectionString, x => x.MigrationsHistoryTable("__HuMigrationsHistory"))
                        .LogTo(Console.WriteLine, LogLevel.Information);//输出日志，可以自定义配置NLog等日志输出
                    break;
                case "mysql":
                    //optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), x => x.MigrationsHistoryTable("__HuMigrationsHistory"));
                    break;
                // 扩展其他数据库提供程序...
                default:
                    throw new NotSupportedException($"未找到对应的数据库支持： '{databaseProvider}' ");
            }

            // 启用敏感日志（可选，仅在开发环境使用）
            optionsBuilder.EnableSensitiveDataLogging();

            //
            //optionsBuilder.UseBatchEF_MSSQL();

            base.OnConfiguring(optionsBuilder);
        }
    }
}
